<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP 'buttonList.jsp' starting page</title>    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<script type="text/javascript" src="js/jquery-1.8.3.min.js"></script>
	<link rel="stylesheet" type="text/css"
			href="js/easyUI/themes/default/easyui.css">
	<link rel="stylesheet" type="text/css"
			href="js/easyUI/themes/icon.css">
	<script type="text/javascript"
			src="js/easyUI/jquery.easyui.min.js"></script>
	<script type="text/javascript"
			src="js/easyUI/locale/easyui-lang-zh_CN.js"></script>
	<link rel="stylesheet" type="text/css"
			href="css/myCss.css">
	<script type="text/javascript">
	var butgrid;
	$(function(){
	    $('#rolegrid').datagrid({ 
	        title:'角色列表', 
	        url:"role/queryRoleListByPage",
	        rownumbers:true,//行号 
	        nowrap:true,
	        pagination :true, 
	        pageNumber:1,
	        pageSize:10,
	        pageList:[10,20,30,40,50],
	        pagePosition:'bottom',
	        striped:true,
	        fit:true,
	        fitColumns:true,
	        singleSelect:true,//是否单选 
	        columns:[[
				{field:'roleId',title:'编码',width:200,hidden:'true'},
				{field:'roleName',title:'名称',width:150,align:'center'},
				{field:'enabled',title:'是否可用',width:90,align:'center', formatter: imgcheckbox},
				{field:'roleDesc',title:'备注',width:200,align:'center'},
				{field:'optRoleUrl',title:'操作',width:250,align:'center'}
	        ]],
	        toolbar: [{ 
	            text: '添加', 
	            iconCls: 'icon-add', 
	            handler: function() { 
	               	$('#addRoleId').dialog('open').dialog('setTitle','添加');
					$("#titleId").html("添加角色");
					$('#fmbut').form('clear');
					$("#isAbleId").attr("checked","checked");
	            } 
	        }, '-', { 
	            text: '修改', 
	            iconCls: 'icon-edit', 
	            handler: function() { 
	               	var row = $('#rolegrid').datagrid('getSelected');
					if (row){
						$('#addRoleId').dialog('open').dialog('setTitle','修改');
						$("#titleId").html("修改角色");
						url = 'role/loadRoleById?roleId='+row.roleId;
						$('#fmbut').form('load',url);
					}else{
						$.messager.alert('提示','请选择你要删除的角色!','warning');
					}
	            } 
	        }, '-',{ 
	            text: '删除', 
	            iconCls: 'icon-remove', 
	            handler: function(){ 
	                var row = $('#rolegrid').datagrid('getSelected');
					if (row){
						$.messager.confirm('提示','你确定删除【'+row.roleName+'】?',function(r){
							if (r){
								$.ajax({
									type: "POST",
									url: "role/deleteRole",
									data: {roleId:row.roleId},
									success: function(data){
										var obj = eval('('+data+')');
										if (obj.result==1){
											$('#rolegrid').datagrid("reload"); 
											$.messager.show({    // show error message
												title: '提示',
												msg: obj.errorMsg
											}); 
										} else {
											$.messager.show({    // show error message
												title: '提示',
												msg: obj.errorMsg
											});
										}
									}
								});
							}
						});
					}else{
						$.messager.alert('提示','请选择你要删除的角色!','warning');
					}
	            } 
	        },'-',{
				iconCls: 'icon-reload',
				text:'刷新',
				handler: function(){
				   $('#rolegrid').datagrid("reload");
				}
			}]
	    });
	});
	
	
	//保存按键
	function saveRole(){
	        url = "role/saveRole"
            $('#fmbut').form('submit',{
                url: url,
                onSubmit: function(){
                    return $(this).form('validate');
                },
                success: function(data){
                    var obj = eval('('+data+')');
                    if (obj.result==2){
                        $.messager.show({
                            title: 'Error',
                            msg: result.errorMsg
                        });
                    } else {
                        $('#addRoleId').dialog('close');        // close the dialog
                        $('#rolegrid').datagrid("reload");    // reload the user data
                    }
                }
            });
	}
	
	
	
	//分配角色给用户
	function giveRoleToUsers(roleId,roleName){
	    $('#userRoleId').show();
	    $("#userRolesDiv").html("");
	    $("#roleToUser").html(roleId);
		$('#userRoleId').dialog({ 
		title:'查看角色用户-'+roleName, 
		width:$(window).width() * 0.8,
		height:$(window).height() * 0.95,
		padding:5,
		modal:true,
		buttons: [{ 
			text: '关闭', 
			handler: function() { 
				$('#userRoleId').dialog('close'); 
			} 
		}] 
		}); 
		
		
		//组织树
	    $('#treeOrg').tree({
               url:'org/queryOrgTreeToUser?parCode=1',
               lines:true,
               animate:true,
			   onBeforeExpand:function(node,param){                         
			        $('#treeOrg').tree('options').url = "org/queryOrgTreeToUser?parCode="+node.id;  
		       },
               onClick:function(node){  
			        $("#orgCodeToUser").html(node.id);
			        var userUrl = "user/queryAllUserByOrgCodeToRole?orgCode="+node.id+"&roleId="+roleId;
			         $.ajax({
						   type: "POST",
						   url: userUrl,
						   success: function(data){
							   var obj = eval('('+data+')');
	                           if (obj.result==1){
	                                var userHtml = "";
	                                if(obj.datas.length==0){
	                                    userHtml="<div style='color:red;position:absolute;top:50%;left:45%'>没有你要找的数据!</div>"
	                                }else{
	                                    for ( var i = 0; i < obj.datas.length; i++) {
											if(obj.datas[i].sign==1){
											   	   userHtml = userHtml+"<a href='javascript:;' style='text-align:left;' title='"+obj.datas[i].positionName+"'><input type='checkbox' checked='checked' disabled value='"+obj.datas[i].userId+"'/>"+obj.datas[i].userName+"</a>";
											}else{
											   	   userHtml = userHtml+"<a href='javascript:;' style='text-align:left;' title='"+obj.datas[i].positionName+"'><input type='checkbox' disabled value='"+obj.datas[i].userId+"'/>"+obj.datas[i].userName+"</a>";
											} 
								        }
	                                }
								    $("#userRolesDiv").html(userHtml);
	                           } else {
								 $.messager.show({    // show error message
								     title: '提示',
								     msg: obj.errorMsg
								 });
	                           }
						   }
						});
			  },onLoadSuccess : function(row, data) {
						var t = $(this);
						if (data) {
								$(data).each(function(index, d) {
									if (this.state == 'closed') {
									t.tree('expandAll');
								}
							});
						}
			 }
		});
	}
	
	
	//保存角色用户关系
	function saveUserRole(){
		    var roleId = $("#roleToUser").html();
		    var orgCode = $("#orgCodeToUser").html();
		    var str = $("#userRolesDiv input[type='checkbox']");
			var objarray = str.length;
			var strBuffer = "";
			for (i = 0; i < objarray; i++) {
				if (str[i].checked == true) {
						modelid = str[i].value;
						strBuffer += modelid;
						strBuffer += ",";
			    }
			}
			
			if($("#userRolesDiv input[type='checkbox']:checked").size()>0){
			    $.ajax({
				url : 'role/saveUserToRole',
				data : {
					strBuffer:strBuffer,
					roleId:roleId,
					orgCode:orgCode
				},
				success : function(data) {
					var obj = eval('('+data+')');
	                if (obj.result==1){
					    $.messager.show({
							msg :  obj.errorMsg,
							title : '提示'
					    });
					    $('#userRoleId').dialog('close'); 
					} else {
						$.messager.show({
							msg :  obj.errorMsg,
							title : '提示'
					    });
					}
				}
			  });
			}else{
			   $.messager.show({
					msg :  "请选择你要设置的角色!",
					title : '提示'
					});
			}
	}
	
	//给角色分配菜单
	function giveRoleToMenu(roleId,roleName){
	    $('#menuRoleId').show();
	    $("#roleToMenu").html(roleId);
		$('#menuRoleId').dialog({ 
		title:'设置菜单-角色'+roleName, 
		width:$(window).width() * 0.4,
		height:$(window).height() * 0.95,
		padding:5,
		modal:true,
		buttons: [{ 
			text: '提交', 
			handler: function() { 
				saveMenuRole();
			} 
		}, { 
			text: '取消', 
			handler: function() { 
				$('#menuRoleId').dialog('close'); 
			} 
		}] 
		}); 
		
		
		//菜单树
	    $('#menuTree').tree({
               url:'menu/queryMenuTreeToRole?parCode=1&roleId='+roleId,
               lines:true,
               animate:true,
               checkbox:true,
               onlyLeafCheck:true,
			   onBeforeExpand:function(node,param){                         
			        $('#menuTree').tree('options').url = "menu/queryMenuTreeToRole?parCode="+node.id+"&roleId="+roleId;  
		       },onLoadSuccess : function(row, data) {
					var t = $(this);
					if (data) {
						$(data).each(function(index, d) {
							if (this.state == 'closed') {
								t.tree('expandAll');
							}
						});
					}
			 }
		});
	}
	
	//给角色分配选项卡
	function giveRoleToTabs(roleId,roleName){
	    $('#tabRoleId').show();
	    $("#roleToTabId").html(roleId);
		$('#tabRoleId').dialog({ 
		title:'设置选项卡-角色'+roleName, 
		width:$(window).width() * 0.8,
		height:$(window).height() * 0.95,
		padding:5,
		modal:true,
		buttons: [{ 
			text: '提交', 
			handler: function() { 
				saveMenuRoleTabs();
			} 
		}, { 
			text: '取消', 
			handler: function() { 
				$('#tabRoleId').dialog('close'); 
			} 
		}] 
		}); 
		
		
		//获取菜单树
		    $('#tabTreeGrid').treegrid({
			url : 'menu/queryMenusAndTabTreeGrid?parCode=1&roleId='+roleId,
			fit : true,
			animate:true,
			border : false,
			idField:'id',    
			treeField : 'menuName',
			onBeforeExpand:function(node,param){                         
			        $('#tabTreeGrid').treegrid('options').url = "menu/queryMenusAndTabTreeGrid?parCode="+node.id+"&roleId="+roleId;  
		    }, 
			onLoadSuccess : function(row, data) {  //加载展开
				var t = $(this);
				if (data) {
					$(data).each(function(index, d) {
						if (this.state == 'closed') {
							t.treegrid('expandAll');
						}
					});
				}
			 }
		});
	}
	
	
	//给角色分配按钮
	function giveRoleToButs(roleId,roleName){
	    $('#butRoleId').show();
	    $("#roleToButId").html(roleId);
		$('#butRoleId').dialog({ 
		title:'设置按钮-角色'+roleName, 
		width:$(window).width() * 0.8,
		height:$(window).height() * 0.95,
		padding:5,
		modal:true,
		buttons: [{ 
			text: '提交', 
			handler: function() { 
				saveMenuRoleButs();
			} 
		}, { 
			text: '取消', 
			handler: function() { 
				$('#butRoleId').dialog('close'); 
			} 
		}] 
		}); 
		
		
		//获取菜单树
		    $('#butTreeGrid').treegrid({
			url : 'menu/queryMenusAndButTreeGrid?parCode=1&roleId='+roleId,
			fit : true,
			animate:true,
			border : false,
			idField:'id',    
			treeField : 'menuName',
			onBeforeExpand:function(node,param){                         
			        $('#butTreeGrid').treegrid('options').url = "menu/queryMenusAndButTreeGrid?parCode="+node.id+"&roleId="+roleId;  
		    }, 
			onLoadSuccess : function(row, data) {  //加载展开
				var t = $(this);
				if (data) {
					$(data).each(function(index, d) {
						if (this.state == 'closed') {
							t.treegrid('expandAll');
						}
					});
				}
			 }
		});
	}
	
	
	//保存角色选项卡
	function saveMenuRoleTabs(){
	    var roleId = $("#roleToTabId").html();
	    var checks = $(".tab1s");
	    var strBuffer = "";
		var objarray = checks.length;
			var strBuffer = "";
			for (i = 0; i < objarray; i++) {
				if (checks[i].checked == true) {
					modelid = checks[i].value;
					strBuffer += modelid;
					strBuffer += "#";
				}
			}
			
	   //提交数据
	   $.ajax({
				url : 'role/saveTabsMenuToRole',
				data : {
					strBuffer:strBuffer,
					roleId:roleId
				},
				success : function(data) {
					var obj = eval('('+data+')');
	                if (obj.result==1){
					    $.messager.show({
							msg :  obj.errorMsg,
							title : '提示'
					    });
					    $('#tabRoleId').dialog('close'); 
					} else {
						$.messager.show({
							msg :  obj.errorMsg,
							title : '提示'
					    });
					}
				}
			  });
	}
	
	
	//保存角色按键
	function saveMenuRoleButs(){
	    var roleId = $("#roleToButId").html();
	    var checks = $(".buttons");
	    var strBuffer = "";
		var objarray = checks.length;
			var strBuffer = "";
			for (i = 0; i < objarray; i++) {
				if (checks[i].checked == true) {
					modelid = checks[i].value;
					strBuffer += modelid;
					strBuffer += "#";
				}
			}
			
	   //提交数据
	   $.ajax({
				url : 'role/saveButsMenuToRole',
				data : {
					strBuffer:strBuffer,
					roleId:roleId
				},
				success : function(data) {
					var obj = eval('('+data+')');
	                if (obj.result==1){
					    $.messager.show({
							msg :  obj.errorMsg,
							title : '提示'
					    });
					    $('#butRoleId').dialog('close'); 
					} else {
						$.messager.show({
							msg :  obj.errorMsg,
							title : '提示'
					    });
					}
				}
			  });
	}
	
	//保存角色菜单
	function saveMenuRole(){
            var roleId = $("#roleToMenu").html();
            var nodes = $('#menuTree').tree('getChecked');
            var strBuffer = '';
            for(var i=0; i<nodes.length; i++){
                if (strBuffer != '') 
                strBuffer += ',';
                strBuffer += nodes[i].id;
            }
            
            $.ajax({
				url : 'role/saveMenuToRole',
				data : {
					strBuffer:strBuffer,
					roleId:roleId//,
					//orgCode:orgCode
				},
				success : function(data) {
					var obj = eval('('+data+')');
	                if (obj.result==1){
					    $.messager.show({
							msg :  obj.errorMsg,
							title : '提示'
					    });
					    $('#menuRoleId').dialog('close'); 
					} else {
						$.messager.show({
							msg :  obj.errorMsg,
							title : '提示'
					    });
					}
				}
			  });
    }
        
	//是否可用图标显示
	var imgcheckbox = function (cellvalue, options, rowObject) {
                return cellvalue ? '<img src="images/icon/can.png" alt="正常" title="正常" />' : '<img src="images/icon/not.png" alt="禁用" title="禁用" />';  
    }; 
    //全选
    function allSelect(cellvalue, options, rowObject){
        return "<input onclick=selectAlls('"+options.id+"') val='1' id="+options.id+" type='checkbox'>";
    }
    
    //全部选择项
    function selectAlls(menuCode){
        var fVal = $("#"+menuCode).val();
        if(fVal){
           $(".but"+menuCode).each(function(){this.checked=true;}); 
           $(".tab"+menuCode).each(function(){this.checked=true;}); 
           $("#"+menuCode).val(0)
        }
        
        if(fVal==0){
           $(".but"+menuCode).each(function(){this.checked=false;}); 
           $(".tab"+menuCode).each(function(){this.checked=false;});
           $("#"+menuCode).val(1)
        }
    }
    
    
	</script>

    <style type="text/css">
    .form_label{
    text-align:right;
    }
    </style>
  
  <body class="easyui-layout">
        <div region="center" border="false">
			<table id="rolegrid">
			</table>
		</div>
		
		<!-- 添加用户界面 -->
  <div id="addRoleId" class="easyui-dialog"
			style="width: 400px; height: 300px; text-align: center; padding: 10px 20px"
			closed="true" data-options="modal:true">
			<form method="post" id="fmbut" >
				<h2 id="titleId"></h2>
				<input name="roleId" style="display:none;"/>
				<table width="300px" align="center" style="align: center" border="0">
					<tr>
						<td class="form_label" style="width:150xp;">名称：</td>
						<td class="form_content" ><input name="roleName" class="easyui-validatebox" data-options="required:true" maxlength="32"></input></td>
					</tr>
					<tr>
						<td class="form_label">备注：</td>
						<td class="form_content" ><textarea style="height:60px;width:200px" name="roleDesc"></textarea></td>
					</tr>
					<tr>
						<td class="form_label">是否可用：</td>
						<td class="form_content" >
						<input type="radio" name="enabled" value="1" id="isAbleId"/>可用&nbsp;&nbsp;
                        <input type="radio" name="enabled" value="0" id="noAbleId"/>禁用&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
						</td>
					</tr>
					<tr>
						<td class="form_label" colspan="2" style="text-align: center">
							<a href="javascript:void(0)" onclick="saveRole()" class="easyui-linkbutton">保存</a>
							<a href="javascript:void(0)" class="easyui-linkbutton" onclick="javascript:$('#addRoleId').dialog('close')">取消</a>
						</td>
					</tr>
				</table>
			</form>
		</div>
	<!-- end添加用户界面 -->
	
	   <!-- 设置用户 -->
		<div id="userRoleId" style="display:none;">
		     <span id="roleToUser" style="display:none;"></span>
		     <span id="orgCodeToUser" style="display:none;"></span>
		     <div class="easyui-layout" data-options="fit:true">
		       	<div data-options="region:'west',split:true,title:'组织机构'" style="width:300px">
		       	    <div>
						<ul id="treeOrg" class="ztree">
						</ul>
					</div>
		       	</div>
	            <div data-options="region:'center',title:'此角色对应的用户'" style="padding:10px;">
	                 <div id="userRolesDiv" class="Cbox" style="width:95%">
	                       
	                 </div>
	            </div>
		     </div>
		</div>
		
		
		 <!-- 设置菜单 -->
		<div id="menuRoleId" style="display:none;">
		     <span id="roleToMenu" style="display:none;"></span>
		     <div class="easyui-layout" >
	            <div class="easyui-tabs" >
	                  <!-- 菜单设置 -->
	                  <div title="选择菜单" style="padding:10px;height:100%;">
	                       <ul id="menuTree" class="easyui-tree"></ul>
	                  </div>
	            </div>
		     </div>
		</div>
		
		<!-- 设置选项卡-->
		<div id="tabRoleId" style="display:none;">
		     <span id="roleToTabId" style="display:none;"></span>
		     <div class="easyui-layout" data-options="fit:true">
	                  <div title="选择菜单选项卡" style="padding:0px;height:98%;">
	                      <table id="tabTreeGrid" >
	                          <thead>
	                         <tr>
	                           <th data-options="field:'id'" width="20" hidden="true">id</th>
	                           <th data-options="field:'menuName'" width="150" align="left">菜单名称</th>
	                           <th data-options="field:'aselect',formatter:allSelect" width="50"align="center">全选</th>
	                           <th data-options="field:'selectTab'" align="center">选择选项卡</th>
	                         </tr>
	                         </thead>
	                      </table>
	                  </div>
		     </div>
		</div>
		
		 <!-- 设置按钮 -->
		<div id="butRoleId" style="display:none;">
		     <span id="roleToButId" style="display:none;"></span>
		     <div class="easyui-layout" data-options="fit:true">
	                  <div title="选择菜单按钮" style="padding:0px;height:98%;">
	                      <table id="butTreeGrid" >
	                          <thead>
	                         <tr>
	                           <th data-options="field:'id'" width="20" hidden="true">id</th>
	                           <th data-options="field:'menuName'" width="150" align="left">菜单名称</th>
	                           <th data-options="field:'aselect',formatter:allSelect" width="50"align="center">全选</th>
	                           <th data-options="field:'selectopt'" align="center">按钮选项</th>
	                         </tr>
	                         </thead>
	                      </table>
	                  </div>
		     </div>
		</div>
  </body>
</html>
